/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.rehan.commons;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class PidExctractor {

    private final Document doc;
    private final XPath xpath;

    /**
     *
     * @param doc
     * @param xpath XPath that selects all elements, that contain pid
     */
    public PidExctractor(Document doc, String xpath) {
        this.doc = doc;
        this.xpath = Dom4jUtils.createXPath(xpath);
    }

    public PidExctractor(File documentFile, String xpath) throws FileNotFoundException, DocumentException {
        this(Dom4jUtils.loadDocument(documentFile, false), xpath);
    }

    public Set<String> extractPids() {
        List<Element> elements = xpath.selectNodes(doc);
        return toPidSet(elements);
    }

    public void extractPidsAndSaveToFile(File file) throws IOException {
        Set<String> pids = extractPids();
        FileWriter out = new FileWriter(file);
        for (String pid : pids) {
            out.write(pid);
            out.write("\n");
        }
        out.close();
    }

    private Set<String> toPidSet(List<Element> elements) {
        Set<String> result = new HashSet<String>();
        for (Element element : elements) {
            result.add(element.getText());
        }
        return result;
    }
}
